package com.gzk.hrm.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.gzk.hrm.constatns.SystemConstants;
import com.gzk.hrm.domain.Employee;
import com.gzk.hrm.domain.Login;
import com.gzk.hrm.domain.Tenant;
import com.gzk.hrm.dto.AuditMessageDto;
import com.gzk.hrm.dto.TenantRegisterDto;
import com.gzk.hrm.exception.GlobalException;
import com.gzk.hrm.feign.AuthLoginFeign;
import com.gzk.hrm.mapper.TenantMapper;
import com.gzk.hrm.service.IEmployeeService;
import com.gzk.hrm.service.ITenantService;
import com.gzk.hrm.util.AjaxResult;
import com.gzk.hrm.util.AssertUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jake.Chen
 * @since 2022-01-25
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {

    @Autowired
    private AuthLoginFeign authLoginFeign;

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private TenantMapper tenantMapper;
    @Autowired
    private RestTemplate restTemplate;

    @Value("${hrm.mealTryDays}")
    private int mealTryDays;

    @Override
    public void entering(TenantRegisterDto dto) {
        //@todo 判断非空

        //判断两次密码是否一致
        /*if(!dto.getConfirmPassword().equals(dto.getLogin().getPassword())){
            throw new
        }*/

        //判断公司名是否为空
        //AssertUtils.isEmpty(dto.getTenant().getCompanyName(), "公司名不能为空！");

        //判断公司资质
        //AssertUtils.isTrue(ValidatorUtils.isLicense(dto.getTenant().getCompanyNum()), "公司统一认证码格式不对");

        //
        //判断公司名是否存在
        Wrapper<Tenant> wrapper = new EntityWrapper();
        wrapper.eq("company_name", dto.getTenant().getCompanyName());
        List<Tenant> tenants = baseMapper.selectList(wrapper);

        AssertUtils.isEmpty(tenants, "公司名已经存在！");


        //先保存login信息
        Login login = dto.getLogin();
        //前台
        login.setType(1);
        //保存机构信息
        AjaxResult res = authLoginFeign.save(login);
        Object loginId = res.getResultObj();

        //保存套餐和机构的中间表
        Map<String,Object> map = new HashMap<>();
        map.put("loginId",loginId );
        map.put("mealId", dto.getMealId());
        map.put("expireDate", DateUtils.addDays(new Date(), mealTryDays));
        authLoginFeign.saveLoginMeal(map);

        //保存employee
        Employee employee = dto.getEmployee();
        employee.setInputTime(new Date());
        employee.setRealName("张三");
        employee.setState(Employee.NORMAL);
        employee.setType(5);
        employee.setLoginId(Long.valueOf(loginId.toString()));
        //保存
        employeeService.insert(employee);

        //保存tenant
        Tenant tenant = dto.getTenant();
        tenant.setAdminId(employee.getId());
        tenant.setState(0);
        tenant.setRegisterTime(new Date());
        tenantMapper.insert(tenant);

        //保存login的机构信息
        login.setTenantId(tenant.getId());
        login.setTenantName(tenant.getCompanyName());
        authLoginFeign.save(login);

    }

    @Override
    public void verifyCompanyNum(Map<String,String> map) {
        //校验格式
        //AssertUtils.isTrue(ValidatorUtils.isLicense(map.get("companyNum")), "公司资质格式不正确！");
        //调用第三方接口判断是否正确
        ResponseEntity<Map> forEntity = restTemplate.getForEntity(SystemConstants.TENANT_VERIFY_HTTP.replace("COMPANYNAME",map.get("companyName")).replace("APPKEY", SystemConstants.APPKEY), Map.class);
        // 返回的数据
        Map body = forEntity.getBody();
        Map result = (Map)body.get("result");
        Integer status =(Integer) result.get("status");
        if (status == 200){
            result = (Map)result.get("result");
            String creditCode = (String)result.get("creditCode");
            System.out.println(creditCode);
            System.out.println("==============");
            System.out.println(map.get("companyName"));
            AssertUtils.isTrue(map.get("companyNum").equals(creditCode),"企业统一社会码不正确！" );
        }else {
            throw new GlobalException("企业信息异常！");
        }

    }

    @Override
    public void confirmByEamil(AuditMessageDto auditMessageDto) throws MessagingException {
        //公司id
        Long id = auditMessageDto.getId();
        //备注信息
        String auditRemark = auditMessageDto.getAuditRemark();
        //查询公司信息
        Tenant tenant = selectById(id);
        //修改公司状态为审核通过待激活
        tenant.setState(Tenant.STATE_AUDIT_SUCCESS);
        //保存
        updateById(tenant);
        //根据adminId查询emp管理员
        Employee employee = employeeService.selectById(tenant.getAdminId());
        //得到管理员邮箱
        String email = employee.getEmail();


        //创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
        helper.setFrom("694754772@qq.com");
        helper.setSubject("审核通过，请激活");

        helper.setText("<h3>您的公司审核已经通过，请点击链接，前往确认激活！</h3>"+"<br/>"+"审核备注信息："+auditRemark+"<br/>"+
                "http://localhost:10300/hrm/system/tenant/activation/"+auditMessageDto.getId() ,true);
        helper.setTo(email);


        javaMailSender.send(mimeMessage);
    }

    /**
     * 激活邮件
     * @param id
     */
    @Override
    public void activation(Long id) {
        //查询公司信息
        Tenant tenant = selectById(id);
        //修改状态为2，激活 0
        tenant.setState(Tenant.STATE_ACTIVE_SUCCESS);
        //保存
        updateById(tenant);
    }

}
